﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using ShopB2C.Enums;

namespace ShopB2C.Helper {
    /// <summary>
    /// 随机码图片 ActionResult
    /// ，指定随机字符 ViewData["RandomString"] = "abc"
    /// ，未指定默认 4 位长度的字母数字组成的字符串
    /// ，Session 的 Key 为 "RandCode"
    /// </summary>
    public class RandImageResult : ActionResult {
        public override void ExecuteResult(ControllerContext context) {
            var session = context.HttpContext.Session;
            var response = context.HttpContext.Response;
            var randCode = context.Controller.ViewData.ContainsKey("RandomString")
                ? context.Controller.ViewData["RandomString"].ToString()
                : RandomHelper.RandomString(4, RandomType.LetterAndNum);
            // Session 保存
            session.Add("RandCode", SecurityHelper.SHA256Hash(randCode.ToLower()));
            // 图片存入内存流
            Bitmap bitmap = RandomHelper.RandomImage(randCode, true);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Gif);
            // 输出
            response.Clear();
            response.ContentType = Methods.GetContentTypeByExtentsion(".jpg");
            response.BinaryWrite(ms.GetBuffer());
            // 资源释放
            bitmap.Dispose();
            ms.Close();
            ms.Dispose();
        }
    }
}
